package com.Hwadee.eduservice.controller.fron;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.Hwadee.commonutils.R;
import com.Hwadee.eduservice.entity.EduArticle;
import com.Hwadee.eduservice.service.EduArticleService;
import com.Hwadee.servicebase.exceptionHandler.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author testjava
 * @since 2021-07-17
 */
@RestController
@RequestMapping("/eduservice/article")
public class EduArticleController {

    @Autowired
    private EduArticleService articleService;

    //分页查询article（前台）
    @GetMapping("/getArticleFrontList/{current}/{limit}")
    public R getArticleList(@PathVariable("current") long current,
                                 @PathVariable("limit") long limit) {
        Page<EduArticle> pageArticle = new Page<>(current, limit);
        Map<String, Object> map = articleService.getArticleList(pageArticle);
        //返回分页中所有数据
        return R.ok().data(map);
    }

    //分页查询article（后台）
    @GetMapping("/getArticleAdminList/{current}/{limit}")
    public R getArticleListAdmin(@PathVariable("current") long current,
                            @PathVariable("limit") long limit) {
        Page<EduArticle> pageArticle = new Page<>(current, limit);
        Map<String, Object> map = articleService.getArticleAdmin(pageArticle);
        //返回分页中所有数据
        return R.ok().data(map);
    }

    //删除article
    @DeleteMapping("/deleteArticle/{id}")
    public R deleteArticle(@PathVariable("id") String id){
        boolean remove = articleService.removeById(id);
        if (remove) {
            return R.ok().message("移除文章成功！");
        }
        else {
            return R.error().message("移除文章失败！");
        }
    }

    //根据id查询文章信息
    @GetMapping("/getArticle/{id}")
    public R getArticle(@PathVariable("id") String id) {
        EduArticle article = articleService.getById(id);
        return R.ok().data("list", article);
    }

    //更新article
    @PostMapping("/updateArticle")
    public R updateArticle(@RequestBody EduArticle article) {
        boolean update = articleService.updateById(article);
        if (update) {
            return R.ok().message("更新文章成功！");
        }
        else {
            throw new GuliException(20001, "更新文章失败！");
        }
    }

    @PostMapping("/addArticle")
    public R addArticle(@RequestBody EduArticle article) {
        boolean save = articleService.save(article);
        if (save) {
            return R.ok().message("新增文章成功！");
        }
        else {
            throw new GuliException(20001, "新增文章失败！");
        }
    }
}

